import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Objects;
import java.util.Properties;

/**
 * Created by yangxianming on 2017/6/6.
 * 项目启动时的一些必要操作
 */
@WebServlet(name = "SetConfig", urlPatterns = {"/SetConfig"}, loadOnStartup = 1)
public class SetConfig extends HttpServlet{

    @Override
    public void init(ServletConfig config) throws ServletException {
        //把应用的路径写入配置文件 app.properties
        String s = config.getServletContext().getRealPath("/");
        System.out.println("----------start setconfig----------" + s);
        writePath(s);
    }

    private void writePath(String path){
        //有可能在读取配置的时候还没有创建文件
        //写入项目路径配置
        File file = new File(path + "/config/app.properties");
        int i = 0;
        do {
            if (file.exists()){
                Properties properties = new Properties();
                try {
                    properties.load(new FileInputStream(path + "/config/app.properties"));
                }catch (Exception e){
                    e.printStackTrace();
                }
                String appPath = properties.getProperty("appPath");
                if (!Objects.equals(appPath, path)){
                    properties.setProperty("appPath", path);
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(path + "/config/app.properties");
                        properties.store(fileOutputStream, "");
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        System.out.println("++++ addElement config ++++");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                break;
            }else {
                try {
                    file.createNewFile();
                }catch (Exception e){
                    e.printStackTrace();
                }
                i++;
            }
        }while (i < 3);
    }
}
